import { TransformConfig } from '../types';

export class PageTransformer {
  private config: TransformConfig;

  constructor(config: TransformConfig) {
    this.config = config;
  }

  async transform(content: string, filePath: string): Promise<string> {
    // 解析Page对象
    const pageData = this.parsePageObject(content);
    
    // 转换为Taro组件
    return this.generateTaroComponent(pageData, filePath);
  }

  private parsePageObject(content: string): any {
    // 简单的Page对象解析
    const pageMatch = content.match(/Page\s*\(\s*\{([\s\S]*?)\}\s*\)/);
    if (!pageMatch) {
      throw new Error('No Page object found');
    }

    const pageContent = pageMatch[1];
    
    return {
      data: this.extractData(pageContent),
      methods: this.extractMethods(pageContent),
      lifecycle: this.extractLifecycle(pageContent),
      raw: pageContent
    };
  }

  private extractData(content: string): any {
    const dataMatch = content.match(/data\s*:\s*\{([\s\S]*?)\}/);
    if (!dataMatch) return {};
    
    // 简单的数据提取，实际项目中需要更复杂的解析
    return dataMatch[1];
  }

  private extractMethods(content: string): string[] {
    const methods: string[] = [];
    const methodRegex = /(\w+)\s*\([^)]*\)\s*\{/g;
    let match;
    
    while ((match = methodRegex.exec(content)) !== null) {
      const methodName = match[1];
      if (!['onLoad', 'onShow', 'onHide', 'onUnload', 'onReady'].includes(methodName)) {
        methods.push(methodName);
      }
    }
    
    return methods;
  }

  private extractLifecycle(content: string): any {
    const lifecycle: any = {};
    const lifecycleMethods = ['onLoad', 'onShow', 'onHide', 'onUnload', 'onReady'];
    
    lifecycleMethods.forEach(method => {
      const regex = new RegExp(`${method}\\s*\\([^)]*\\)\\s*\\{([\\s\\S]*?)\\}`);
      const match = content.match(regex);
      if (match) {
        lifecycle[method] = match[1];
      }
    });
    
    return lifecycle;
  }

  private generateTaroComponent(pageData: any, filePath: string): string {
    const componentName = this.getComponentName(filePath);
    
    let component = '';
    
    if (this.config.typescript) {
      component += `import React, { useState, useEffect } from 'react';\n`;
      component += `import { View, Text } from '@tarojs/components';\n`;
      component += `import Taro from '@tarojs/taro';\n\n`;
      
      component += `interface ${componentName}Props {\n`;
      component += `  // Add your props here\n`;
      component += `}\n\n`;
      
      component += `const ${componentName}: React.FC<${componentName}Props> = () => {\n`;
    } else {
      component += `import React, { useState, useEffect } from 'react';\n`;
      component += `import { View, Text } from '@tarojs/components';\n`;
      component += `import Taro from '@tarojs/taro';\n\n`;
      
      component += `const ${componentName} = () => {\n`;
    }

    // 转换data为state
    if (this.config.rules.pages.transformData && pageData.data) {
      component += `  // State converted from data\n`;
      component += `  const [state, setState] = useState({\n`;
      component += `    ${this.transformDataToState(pageData.data)}\n`;
      component += `  });\n\n`;
    }

    // 转换生命周期
    if (this.config.rules.pages.transformLifecycle) {
      component += this.transformLifecycle(pageData.lifecycle);
    }

    // 转换方法
    if (this.config.rules.pages.transformMethods) {
      component += this.transformMethods(pageData.methods);
    }

    // 生成JSX
    component += `  return (\n`;
    component += `    <View className="${componentName.toLowerCase()}">\n`;
    component += `      <Text>${componentName} Component</Text>\n`;
    component += `    </View>\n`;
    component += `  );\n`;
    component += `};\n\n`;
    
    component += `export default ${componentName};\n`;

    return component;
  }

  private getComponentName(filePath: string): string {
    const fileName = filePath.split('/').pop()?.replace('.js', '') || 'Page';
    return fileName.charAt(0).toUpperCase() + fileName.slice(1);
  }

  private transformDataToState(data: string): string {
    // 简单的数据转换，实际项目中需要更复杂的解析
    return data.replace(/:/g, ': ').replace(/,/g, ',\n    ');
  }

  private transformLifecycle(lifecycle: any): string {
    let result = '';
    
    if (lifecycle.onLoad) {
      result += `  useEffect(() => {\n`;
      result += `    // onLoad equivalent\n`;
      result += this.transformWxAPI(lifecycle.onLoad);
      result += `  }, []);\n\n`;
    }
    
    if (lifecycle.onShow) {
      result += `  useEffect(() => {\n`;
      result += `    // onShow equivalent\n`;
      result += this.transformWxAPI(lifecycle.onShow);
      result += `  });\n\n`;
    }
    
    return result;
  }

  private transformMethods(methods: string[]): string {
    let result = '';
    
    methods.forEach(method => {
      result += `  const ${method} = () => {\n`;
      result += `    // TODO: Implement ${method}\n`;
      result += `    console.log('${method} called');\n`;
      result += `  };\n\n`;
    });
    
    return result;
  }

  private transformWxAPI(content: string): string {
    // 转换微信API调用
    let transformed = content;
    
    if (this.config.rules.apis.transformWxAPI) {
      // 替换wx API调用
      transformed = transformed.replace(/wx\./g, 'Taro.');
      
      // 应用自定义API映射
      Object.entries(this.config.rules.apis.customAPIMapping).forEach(([oldAPI, newAPI]) => {
        transformed = transformed.replace(new RegExp(oldAPI, 'g'), newAPI);
      });
    }
    
    return transformed;
  }
} 